#region Copyright RenGuiYou. All rights reserved.
//=====================================================
// PandoraFrameWork
// Author:      RenGuiyou
// Feedback: 	mailto:750539605@qq.com
//=====================================================
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using UnityEngine;
using Debug = UnityEngine.Debug;

namespace Pandora
{
    public static class PdrFileUtil
    {
        #region Create
        /// 创建目录
        public static void CreateDirectory(string path)
        {
            path = path.Replace("\\", "/");
            string[] pathArry = path.Split('/');
            StringBuilder sb = new StringBuilder(pathArry[0]);
            for (int i = 1; i < pathArry.Length; i++)
            {
                sb.Append($"/{pathArry[i]}");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
            }
        }

        /// 通过文件路径创建目录
        public static void CreateDirectoryFromFile(string path)
        {
            path = path.Replace("\\", "/");
            int index = path.LastIndexOf("/", StringComparison.Ordinal);
            string dir = path.Substring(0, index);
            CreateDirectory(dir);
        }

        /// 保存Text到文件
        public static void SaveTextToFile(string path, string fileName, string content)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(content);
            SaveBytesToFile(path, fileName, bytes);
        }

        /// 保存Bytes到文件
        public static void SaveBytesToFile(string path, string fileName, byte[] bytes)
        {
            CreateDirectory(path);
            try
            {
                var filePath = Path.Combine(path, fileName);
                Stream stream = File.Open(filePath, FileMode.Create, FileAccess.ReadWrite);
                stream.Write(bytes, 0, bytes.Length);
                stream.Close();
            }
            catch (Exception e)
            {
                Debug.LogError(e.Message);
            }
        }
        #endregion
        #region Delete
        /// 删除目录
        public static void DeleteDirectory(string path)
        {
            try
            {
                if (Directory.Exists(path))
                {
                    DirectoryInfo di = new DirectoryInfo(path);
                    di.Delete(true);
                }
            }
            catch (Exception e)
            {
                Debug.LogError(e.Message);
            }
        }
        /// 删除文件
        public static void DeleteFile(string path)
        {
            try
            {
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
            }
            catch (Exception e)
            {
                Debug.LogError(e.Message);
            }
        }
        #endregion
        #region Copy
        public static void CopyDirectory(string src, string dest, string suffix = "")
        {
            CreateDirectory(dest);
            foreach (string file in Directory.GetFileSystemEntries(src))
            {
                if (File.Exists(file))
                {
                    FileInfo info = new FileInfo(file);
                    if (String.IsNullOrEmpty(suffix) || file.ToLower().EndsWith(suffix.ToLower()))
                    {
                        string fullPath = Path.Combine(dest, info.Name);
                        File.Copy(file, fullPath);
                    }
                }
                if (Directory.Exists(file))
                {
                    DirectoryInfo info = new DirectoryInfo(file);
                    string destName = Path.Combine(dest, info.Name);
                    CopyDirectory(file, destName, suffix);
                }
            }
        }

        public static void CopyDirectoryOverride(string src, string dest, string suffix = "")
        {
            CreateDirectory(dest);
            foreach (string file in Directory.GetFileSystemEntries(src))
            {
                if (File.Exists(file))
                {
                    FileInfo info = new FileInfo(file);
                    if (String.IsNullOrEmpty(suffix) || file.ToLower().EndsWith(suffix.ToLower()))
                    {
                        string fullPath = Path.Combine(dest, info.Name);
                        if (!File.Exists(fullPath))
                        {
                            File.Copy(file, fullPath);
                        }
                    }
                }
                if (Directory.Exists(file))
                {
                    DirectoryInfo info = new DirectoryInfo(file);
                    string destName = Path.Combine(dest, info.Name);
                    CopyDirectoryOverride(file, destName, suffix);
                }
            }
        }

        public static void CopyFile(string src, string dest)
        {
            DeleteFile(dest);
            CreateDirectoryFromFile(dest);
            File.Copy(src, dest);
        }
        #endregion
        #region Read
        /// 从文件读取Text
        public static string ReadTextFromFile(string path, string defaultValue = "")
        {
            string ret = defaultValue;
            FileInfo fi = new FileInfo(path);
            if (fi.Exists)
            {
                StreamReader reader = fi.OpenText();
                ret = reader.ReadToEnd();
                reader.Close();
                reader.Dispose();
            }
            return ret;
        }
        #endregion
        #region Open
        /// 打开文件目录
        public static void OpenFolder(string folder)
        {
            switch (Application.platform)
            {
                case RuntimePlatform.WindowsEditor:
                    Process.Start("Explorer.exe", folder.Replace('/', '\\'));
                    break;
                case RuntimePlatform.OSXEditor:
                    Process.Start("open", folder);
                    break;
            }
        }
        #endregion
        #region GetFile
        /// 获得所有子文件名
        public static List<string> GetFilesName(string path, string suffix = null, List<string> fileList = null)
        {
            return GetFilesNameExact(path, suffix, null, fileList);
        }

        public static List<string> GetFilesNameExact(string path, string suffix = null, string[] banDic = null, List<string> fileList = null)
        {
            if (fileList == null)
            {
                fileList = new List<string>();
            }
            string[] suffixArray = null;
            if (!string.IsNullOrEmpty(suffix))
            {
                suffix = suffix.ToLower();
                suffixArray = suffix.Split(';');
            }
            string[] filesArray = Directory.GetFiles(path);
            foreach (string filePath in filesArray)
            {
                string file = filePath.Replace('\\', '/').ToLower();
                var fileLower = file.ToLower();
                if (!IncludePath(fileLower, banDic) && !fileLower.EndsWith(".meta") && !fileLower.EndsWith(".manifest"))
                {
                    if (suffixArray != null)
                    {
                        foreach (var endSuffix in suffixArray)
                        {
                            if (fileLower.EndsWith(endSuffix))
                            {
                                fileList.Add(file);
                            }
                        }
                    }
                    else
                    {
                        fileList.Add(file);
                    }
                }
            }
            string[] dirsArray = Directory.GetDirectories(path);
            foreach (string dir in dirsArray)
            {
                GetFilesName(dir, suffix, fileList);
            }
            return fileList;
        }

        public static bool IncludePath(string path, string[] banArray)
        {
            if (banArray == null) return false;
            path = path.Replace("\\", "/").ToLower();
            foreach (var s in banArray)
            {
                string dicPath = s.Replace("\\", "/").ToLower();
                if (path.IndexOf($"/{dicPath}/", StringComparison.Ordinal) != -1)
                {
                    return true;
                }
            }
            return false;
        }

        /// 获取所有目录路径全名
        public static string[] GetDirsName(string path)
        {
            DirectoryInfo raw = new DirectoryInfo(path);
            DirectoryInfo[] childDirs = raw.GetDirectories();
            string[] dirsArray = new string[childDirs.Length];
            for (int i = 0; i < childDirs.Length; i++)
            {
                dirsArray[i] = childDirs[i].Name;
            }
            return dirsArray;
        }
        #endregion
    }
}